﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KaytechSoftware.Cms.App.Areas.Admin.Interfaces;
using KaytechSoftware.Cms.App.Areas.Admin.Models.Base;
using KaytechSoftware.Cms.App.Common;
using KaytechSoftware.Cms.Services.Dto;

namespace KaytechSoftware.Cms.App.Areas.Admin.Models.Entities
{
    public class PhotoModel : GridEntityModel, IGridEntityModel<PhotoDto> 
    {
        [Id]
        [Label(ResourceKey = "Id")]
        [Renderer(Type = RendererType.Hidden)]
        public long Id { get; set; }

        [Label(ResourceKey = "Version")]
        [Renderer(Type = RendererType.Hidden)]
        [SkipInGrid]
        public long Version { get; set; }

        [Label(ResourceKey = "Photo")]
        [Renderer(Type = RendererType.Image)]
        [Link(Type = LinkType.Edit)]
        public PhotoDescriptor Photo { get; set; }

        [Label(ResourceKey = "Photo")]
        [Renderer(Type = RendererType.File)]
        [SkipInGrid]
        public HttpPostedFileBase File { get; set; }

        [Label(ResourceKey = "Title")]
        [Renderer(Type = RendererType.TextBox)]
        public string Title { get; set; }

        [Label(ResourceKey = "Description")]
        [Renderer(Type = RendererType.TextArea)]
        public string Description { get; set; }

        [Label(ResourceKey = "PhotoAlbum")]
        [Renderer(Type = RendererType.DropDown, UseCollection = CollectionKey.PhotoAlbum)]
        [SkipInGrid]
        public long PhotoAlbumId { get; set; }

        [Label(ResourceKey = "PhotoAlbum")]
        [Renderer(Type = RendererType.TextBox)]
        [SkipInDetails]
        public string PhotoAlbum { get; set; }

        public GridEntityModel FromDto(PhotoDto dto)
        {
            Id = dto.Id;
            Version = dto.Version;
            Title = dto.Title;
            Description = dto.Description;
            PhotoAlbumId = dto.PhotoAlbumId;
            PhotoAlbum = dto.PhotoAlbumTitle;
            Photo = new PhotoDescriptor {AlbumId = PhotoAlbumId, PhotoId = Id, Version = Version};
            return this;
        }

        public PhotoDto ToDto()
        {
            byte[] data = null;
            if (File != null && File.InputStream != null)
            {
                data = new byte[File.InputStream.Length];
                File.InputStream.Read(data, 0, data.Length);
            }

            return new PhotoDto()
                {
                    Id = Id,
                    Version = Version,
                    Title = Title,
                    Description = Description,
                    PhotoAlbumId = PhotoAlbumId,
                    PhotoAlbumTitle = PhotoAlbum,
                    Data = data
                };
        }
    }
}